package com.mxpio.erp.technology.controller;

import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.technology.entity.WorkUnit;
import com.mxpio.erp.common.technology.service.WorkUnitService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Tag(name = "WorkUnitController", description = "作业单元数据接口")
@RestController
@RequestMapping("/erp/tech/workunit/")
public class WorkUnitController {
	@Autowired
	private WorkUnitService workUnitService;

	@GetMapping("list")
	@Operation(summary = "作业单元列表", description = "获取作业单元列表", method = "GET")
	public Result<List<WorkUnit>> list(Criteria criteria) throws UnsupportedEncodingException {
		List<WorkUnit> items = workUnitService.list(WorkUnit.class, criteria);
		return Result.OK(items);
	}
	
	@GetMapping("page")
	@Operation(summary = "作业单元列表", description = "获取作业单元列表", method = "GET")
	public Result<Page<WorkUnit>> page(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
		Pageable page = PageRequest.of(pageNo-1, pageSize);
		Page<WorkUnit> items = workUnitService.listPage(WorkUnit.class, page, criteria);
		return Result.OK(items);
	}
	
	@GetMapping("list/{workUnitCode}")
	@Operation(summary = "根据workUnitCode获取作业单元", description = "根据workUnitCode获取作业单元", method = "GET")
	public Result<WorkUnit> getById(@PathVariable(name = "workUnitCode", required = true) String workUnitCode) {
		WorkUnit item = workUnitService.getById(WorkUnit.class, workUnitCode);
		return Result.OK(item);
	}
	
	@PostMapping("add")
	@Operation(summary = "新增作业单元", description = "新增作业单元", method = "POST")
	public Result<WorkUnit> add(@RequestBody WorkUnit workUnit) {
		workUnitService.save(workUnit);
		return Result.OK(workUnit);
	}
	
	@PutMapping("edit")
	@Operation(summary = "编辑作业单元", description = "编辑作业单元（全量）", method = "PUT")
	public Result<WorkUnit> edit(@RequestBody WorkUnit workUnit) {
		workUnitService.update(workUnit);
		return Result.OK(workUnit);
	}
	
	@DeleteMapping("remove/{workUnitCode}")
	@Operation(summary = "删除作业单元", description = "删除作业单元", method = "DELETE")
	public Result<Item> remove(@PathVariable(name = "workUnitCode", required = true) String workUnitCode) {
		String[] workUnitCodes = workUnitCode.split(",");
		for(String key : workUnitCodes){
			workUnitService.delete(WorkUnit.class, key);
		}
		return Result.OK();
	}
}
